import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin } from 'antd';
import moment from 'moment';
import { SecondHeaderC, NestedTableC } from '../../../comps';
import myStyle from './index.less';
import { fixedNum } from '../../../utils/utils';
import uuid from 'es6-uuid';

@connect(({ investmentCalendarM, globalM, loading }) => ({
  investmentCalendarM,
  globalM,
  loading,
}))
@Form.create()
export default class TradeC extends PureComponent {
  state = {
    date: '', //当前日期
    portfolioCodeList: undefined, //组合list
    netting: undefined, //总轧差
    columns: undefined,
    dataSource: undefined,
    currentTime: '', //当前时间戳
  };

  componentDidMount() {}

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (
      this.state.currentTime != nextProps.currentTime ||
      this.state.date != nextProps.date ||
      JSON.stringify(nextProps.portfolioCodeList) !== JSON.stringify(this.state.portfolioCodeList)
    ) {
      this.setState(
        {
          portfolioCodeList: nextProps.portfolioCodeList,
          date: nextProps.date,
          currentTime: nextProps.currentTime,
        },
        () => {
          this.queryTradeEvents();
        },
      );
    }
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };
  //查询交易事件
  queryTradeEvents = () => {
    this.setState({
      netting: undefined,
      columns: undefined,
      dataSource: undefined,
    }); //查询之前清除数据
    const { portfolioCodeList, date } = this.state;
    this.props.dispatch({
      type: 'investmentCalendarM/queryTradeEvents',
      payload: {
        portfolioCode: portfolioCodeList,
        date: moment(date).format('YYYYMMDD'),
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.table.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            netting: data.totalNetting,
            columns: data.table.columns || [],
            dataSource: data.table.dataSource || [],
          });
        } else {
          this.setState({
            netting: undefined,
            columns: [],
            dataSource: [],
          });
        }
      },
    });
  };

  // 点击二级表格展开
  onNestedExtend = (expanded, record) => {
    let dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
    let index = dataSource.findIndex((item) => item.key === record.key);
    if (index > -1 && expanded) {
      // 这里写逻辑，处理数据
      dataSource[index].loading = true;
      this.setState(
        {
          dataSource: JSON.parse(JSON.stringify(dataSource)),
        },
        () => {
          record.child?.map((item) => (item.key = uuid(16)));
          record.columns?.map((item) => {
            if (item.key == 'dataDt') {
              item.render = (text) => {
                return text ? moment(text).format('YYYY-MM-DD') : '--';
              };
            } else if (item.key == 'amount') {
              item.align = 'right';
              item.render = (text) => {
                return text ? fixedNum(text, 2) : '--';
              };
            } else {
              item.render = (text) => {
                return text || '--';
              };
            }
          });
          let nestedConfig = {
            columns: record.columns,
            dataSource: record.child,
            rowKey: 'key',
            scroll: { x: '100%', y: 300 },
          };
          dataSource[index].loading = false;
          dataSource[index].nestedConfig = nestedConfig;
          this.setState({
            dataSource,
          });
        },
      );
    }
  };
  render() {
    const { netting, columns, dataSource } = this.state;
    const { loading } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key == 'eventType') {
          item.width = 200;
        } else {
          item.render = (text) => {
            return text ? fixedNum(text, 2) : '--';
          };
        }
      });

    return (
      <div className={myStyle.trade}>
        <div className={myStyle.eventsTitle}>
          <SecondHeaderC title={'交易事件'} />
          <span style={{ fontWeight: 500 }}>{`总轧差: ${fixedNum(netting, 2)}`}</span>
        </div>
        {/* <Spin spinning={loading.effects['investmentCalendarM/queryTradeEvents']} tip='加载中...'> */}
          <NestedTableC rowKey='key' scroll={{ x: '100%' }} columns={columns} dataSource={dataSource} commonHeader={false} onExpand={this.onNestedExtend} hidePage={true} />
        {/* </Spin> */}
      </div>
    );
  }
}
